package com.bw.biz.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.biz.mapper.TbBillMapper;
import com.bw.biz.mapper.TbProductMapper;
import com.bw.biz.pojo.TbBill;
import com.bw.biz.pojo.TbOrder;
import com.bw.biz.mapper.TbOrderMapper;
import com.bw.biz.service.TbOrderService;
import com.bw.biz.vo.ProductVo;
import com.bw.core.creditStatus.BillStatus;
import com.bw.core.creditStatus.DeleteStatus;
import com.bw.core.utils.IdWorker;
import com.bw.core.vo.*;
import com.bw.core.creditStatus.OrderStatus;
import com.bw.core.creditStatus.RiskStatus;
import com.bw.core.result.ResponseResult;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 申请订单表 服务实现类
 * </p>
 *
 * @author lv
 * @since 2021-03-23
 */
@Service
@Component
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder> implements TbOrderService {

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private TbBillMapper billMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    //添加一条订单
    @Override
    public ResponseResult addOrder(ProductVo product) {
        if (product == null){
            return ResponseResult.error(500,"网络超时，请重新操作。");
        }
        //判断用户是否下了两次订单
        ArrayList<Object> arrayList = new ArrayList<>();
        arrayList.add(OrderStatus.ORDER_CHECK_REFUSE);//审核拒绝
        arrayList.add(OrderStatus.ORDER_REFUND_SUCCESS);//已还款
        arrayList.add(OrderStatus.ORDER_CREDIT_FAIL);//放款失败
        //判断该用户是否重新下单
        QueryWrapper<TbOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",1L);
        queryWrapper.notIn("order_status",arrayList);
        List<TbOrder> tbOrders = orderMapper.selectList(queryWrapper);
        if (!CollectionUtil.isEmpty(tbOrders)){
            return ResponseResult.error(404, "不要频繁操作");
        }
        TbOrder order = new TbOrder();
        order.setOrderNo(idWorker.nextId()+"");
        order.setUserId(1L);
        order.setUserName("薛小帅");
        order.setUserIdentityNo("13042520010606****");
        order.setUserPhone("13218921027");
//        order.setProductId(product.getId());//商品编号
        order.setProductId(1L);//商品编号
//        order.setProductDesc(product.getProductDesc());
        order.setProductDesc("借钱不用还了啊，让吕宇航去抓你");
        order.setProductName(product.getProductName());//产品名称
        order.setProductName("超值商品1");//产品名称
//        order.setOrderStatus(OrderStatus.ORDER_CHECK_NONE);//订单状态
        order.setOrderStatus(0);
//        order.setOrderPeriod(product.getProductPeriod());//周期
        order.setOrderPeriod(3);
//        order.setOrderPeriodInterest(product.getProductInterest());//利息费率

        order.setOrderPeriodInterest(new BigDecimal("0.03"));//利息费率
//        order.setOrderPeriodDefaultInterest(product.getProductDefaultInterest());//罚息费率
        order.setOrderPeriodDefaultInterest(new BigDecimal("0.04"));
//        order.setOrderApplyMoney(product.getProductMoney());//申请金额
        order.setOrderApplyMoney(new BigDecimal("3000"));//申请金额
//        order.setOrderToMoney(product.getProductToMoney());//到账金额
        order.setOrderToMoney(new BigDecimal("3000"));//到账金额
//        order.setOrderMsg(product.getOrderMsg());//订单备注
        order.setOrderMsg("赶紧打钱");
        order.setCreateTime(new Date());
        order.setIsDelete(DeleteStatus.NOT_DELETE);
        order.setUpdateTime(new DateTime());
        orderMapper.insert(order);

        //对象转化为JSON,并且扔到MQ中
        OrderRiskVO orderRiskVO = new OrderRiskVO();
        BeanUtils.copyProperties(order,orderRiskVO);

        String toJSONString = JSON.toJSONString(orderRiskVO);
        amqpTemplate.convertAndSend("item_queue",toJSONString);
        return ResponseResult.success(orderRiskVO);
    }


    //监听 风控MQ
    @Override
    public void dispose(String msg) {
        //从mq中拿取消息，并转化为对象
        JSONObject jsonObject = JSONObject.parseObject(msg);
        RiskOrderVO riskOrder = JSONObject.toJavaObject(jsonObject, RiskOrderVO.class);

        System.out.println("监听MQ："+jsonObject);
        QueryWrapper<TbOrder> queryWrapper = new QueryWrapper<>();
        //拒绝后返回
        if (riskOrder.getStatus() == RiskStatus.RISK_CHECK_REFUSE){
            queryWrapper.eq("order_no", riskOrder.getOrderNo());
            TbOrder order = orderMapper.selectList(queryWrapper).get(0);
            //更改订单状态
            order.setOrderStatus(OrderStatus.ORDER_CHECK_REFUSE);
            orderMapper.update(order,queryWrapper);
        }
        //审核通过
        if (riskOrder.getStatus() == RiskStatus.RISK_CHECK_SUCCESS){
            queryWrapper.eq("order_no", riskOrder.getOrderNo());
            TbOrder order = orderMapper.selectList(queryWrapper).get(0);
            //更改订单状态
            order.setOrderStatus(OrderStatus.ORDER_CREDIT_NONE);
            orderMapper.update(order,queryWrapper);

            //创建实体类
            OrderVo orderVo = new OrderVo();
            orderVo.setOrderNo(order.getOrderNo());
            orderVo.setIdentityNo(order.getUserIdentityNo());
            orderVo.setPayAmount(order.getOrderToMoney());
            orderVo.setStatus(OrderStatus.ORDER_CREDIT_NONE);
            orderVo.setUserId(order.getUserId());
            orderVo.setUserName(order.getUserName());
            //向mq发送消息
            String toJSONString = JSON.toJSONString(orderVo);
            System.out.println("给汪兴达的数据---------------------------------------------");
            System.out.println(toJSONString);
            System.out.println("给汪兴达的数据---------------------------------------------");
            amqpTemplate.convertAndSend("item_order",toJSONString);

        }
    }

    //定时器做补偿
    @PostConstruct
    public void timing(){
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                System.out.println("定时补偿正常启动中");
                HashMap<String, Object> map = new HashMap<>();
                map.put("order_status",0);
                List<TbOrder> orders = orderMapper.selectByMap(map);
                for (TbOrder order : orders) {
                    String toJSONString = JSON.toJSONString(order);
                    amqpTemplate.convertAndSend("item_queue",toJSONString);
                }
            }
        },  3000,1000*60*3);
    }

    //生成账单
    @Override
    public void generateBill(String msg) {
        //监听MQ中的数据
        JSONObject jsonObject = JSONObject.parseObject(msg);
        RepaymentVo repaymentVo = JSONObject.toJavaObject(jsonObject, RepaymentVo.class);
        //根据订单编号查询订单
        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",repaymentVo.getOrderNo());
        TbOrder order = orderMapper.selectList(wrapper).get(0);

        //分为几期
        Integer period = order.getOrderPeriod();
        //每期应还多少钱
        //利息率 * 贷款金额 = 利息
        BigDecimal interest = order.getOrderPeriodInterest().multiply(order.getOrderApplyMoney());
        //利息 + 贷款金额 = 总金额
        BigDecimal totalAmount = interest.add(order.getOrderApplyMoney());
        //总金额 / 多少期 = 每期
        BigDecimal each  = totalAmount.divide(BigDecimal.valueOf(order.getOrderPeriod()));
        for(Integer i = 1; i <= period; i++){
            //开始时间
            DateTime dateTime1 = DateUtil.offsetMonth(order.getCreateTime(), i-1);
            DateTime dateTime2 = DateUtil.offsetDay(dateTime1, 1);
            DateTime dateTime3 = DateUtil.beginOfDay(dateTime2);
            //结束时间
            DateTime dateTime4 = DateUtil.offsetMonth(dateTime3, 1);

            //生成账单表
            TbBill bill = new TbBill();
            bill.setOrderNo(repaymentVo.getOrderNo());//订单编号
            bill.setBillNo(idWorker.nextId()+"");//账单编号
            bill.setBillStatus(BillStatus.BILL_NOE_YET_DUE);//账单状态：未到期
            if (i == 1){
                bill.setBillStatus(BillStatus.BILL_NONE_REFUND);//账单状态：待还款
            }
            bill.setBillPeriod(i);//账单期数
            bill.setProductName(order.getProductName());//产品名称
            bill.setOverdue(0);//逾期天数
            bill.setStartDate(dateTime3);//开始时间
            bill.setEndDate(dateTime4); //结束时间
            //还款时间
            bill.setRefoundMoney(each);//应还金额
            //实际还款金额
            bill.setRefoundStyle(1);//还款方式
            bill.setRefoundInterestMoney(order.getOrderApplyMoney().multiply(order.getOrderPeriodInterest()));//利息金额
            //罚息金额
            bill.setRefoundPrincipal(order.getOrderApplyMoney());//本金
            //总共应还金额
            bill.setCreateDate(new Date());//创建时间
            bill.setIsDelete(DeleteStatus.NOT_DELETE);//是否删除
            bill.setUpdateTime(new Date());
            billMapper.insert(bill);
        }
    }

    //汪兴达 。。。。查询订单
    @Override
    public FindOneOrderResVo findOneOrder(String orderNo) {

        Map<String,Object> columnMap = new HashMap<>();
        columnMap.put("order_no",orderNo);//写表中的列名
        List<TbOrder> employees = orderMapper.selectByMap(columnMap);
        if(CollectionUtil.isEmpty(employees)){
            return null;
        }
        System.out.println(employees.size());
        FindOneOrderResVo findOneOrderResVo = new FindOneOrderResVo();
        BeanUtils.copyProperties(employees.get(0),findOneOrderResVo);

        return findOneOrderResVo;
    }


}